package com.hzdl.library.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.hzdl.library.domain.ReaderInfo;
import com.hzdl.library.domain.ResultInfo;
import com.hzdl.library.service.AddReaderService;
import com.hzdl.library.service.SelectUserByOne;
import com.hzdl.library.service.impl.AddReaderServiceImpl;
import com.hzdl.library.domain.*;

import com.hzdl.library.service.UserService;
import com.hzdl.library.service.impl.SelectUserByOneImpl;
import com.hzdl.library.service.impl.UserServiceImpl;
import com.hzdl.library.util.JDBCUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
@SuppressWarnings("all")
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();
    ObjectMapper objectMapper = new ObjectMapper();
    ResultInfo resultInfo = new ResultInfo();
    AddReaderService addReaderService = new AddReaderServiceImpl();
    SelectUserByOne selectUserByOne = new SelectUserByOneImpl();

    //ResultInfo resultInfo = new ResultInfo();
    //借书
    public void lendBook(HttpServletRequest req, HttpServletResponse resp) {
        //书名
        String name = req.getParameter("name");
        String page = req.getParameter("page");
       /* try {
            name = URLDecoder.decode(name, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        //读者证号
//        String readerId1 = req.getParameter("readerId");
//        Integer readerId2 = Integer.parseInt(readerId1);
//        Integer state = userService.lend(name, readerId2);
        Integer readerId = Integer.parseInt(req.getParameter("readerId"));
        Integer state = userService.lend(name, readerId);

        //state=1,可以借
        if (state == 1) {
            //借书成功
            try {
                if("2".equals(page))
                    state = 2;
                else
                    state = 1;
                objectMapper.writeValue(resp.getOutputStream(), state);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
           /* resultInfo.setErrorMsg("借书成功!");
            resultInfo.setFlag(true);
            try {
                objectMapper.writeValue(resp.getOutputStream(),resultInfo);
            } catch (IOException e) {
                e.printStackTrace();
            }*/
        }
        //不能借
        else {
            try {
                objectMapper.writeValue(resp.getOutputStream(), state);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
            /*else{
            try {
                resp.sendRedirect("/library/admin_books.html?msg='图书借阅失败'");
            } catch (IOException e) {
                e.printStackTrace();
            }
            */
    /*resultInfo.setErrorMsg("该书还未归还!");
            resultInfo.setFlag(false);
            try {
                objectMapper.writeValue(resp.getOutputStream(),resultInfo);
            } catch (IOException e) {
                e.printStackTrace();
            }*//*
        }*/

}

    //还书
    public void returnBook(HttpServletRequest req, HttpServletResponse resp) {
        String page = req.getParameter("page");

        //书id
        String book_id1 = req.getParameter("book_id");
        Integer book_id2 = Integer.parseInt(book_id1);
        Integer change = userService.returnBook(book_id2);
        //state=1,已归还

//        if (change == 1) {
//            try {
//                resp.sendRedirect("/library/admin_books.html?msg='图书归还失败'");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        } else {
            //还书成功
            try {
                if("2".equals(page)) {
//                    response.sendRedirect(request.getContextPath()+"/admin_lend_list.html");
                    resp.sendRedirect(req.getContextPath() + "/reader_book_query.html");
                }else {
//                    resp.sendRedirect("/library/admin_books.html");
                    resp.sendRedirect(req.getContextPath() + "/admin_books.html");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
//        }
    }


    //查询借还日志
    public void lendRecord(HttpServletRequest request, HttpServletResponse response) {
        String text = request.getParameter("text");//搜索的内容
        String cP = request.getParameter("currentPage");
        int currentPage = Integer.parseInt(cP);//当前页
        String r = request.getParameter("rows");
        int rows = Integer.parseInt(r);//每页的条数
        //查询出总条数数totalCount
        Integer totalCount;
        totalCount = userService.findCount(text);
        //计算出总页数totalPage=totalCount%rows==0?totalCount/rows:(totalCount/rows+1)
        Integer totalPage;
        totalPage = totalCount % rows == 0 ? totalCount / rows : (totalCount / rows + 1);
        //计算出索引index=(currentPage-1)*rows;
        Integer index = (currentPage - 1) * rows;
        //分页查询出list
        List<LendList> list = userService.lendRecord(text, index, rows);
        //把所有结果封装进pageBean
        RecordPageBean recordPageBean = new RecordPageBean(rows, totalPage, totalCount, list, currentPage);
        //返回结果给admin_lend_list.html
        try {
            objectMapper.writeValue(response.getOutputStream(), recordPageBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断是借书还是还书
    public void judge(HttpServletRequest request, HttpServletResponse response) {
        //让查询全部图书页面访问此servlet,从班长遍历的集合元素那里获取书名
        String name = request.getParameter("name");
        Integer state = userService.judge(name);
        //state=1可以外借state=0,不能外借可以归还
        //将判断结果返回给班长的查询图书页面进行还书或借阅按钮的拼接
        try {
            objectMapper.writeValue(response.getOutputStream(), state);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //删除一条日志信息
    public void deleteOne(HttpServletRequest request, HttpServletResponse response) {
        String s = request.getParameter("sernum");
        int sernum = Integer.parseInt(s);
        userService.deleteOne(sernum);
        try {
            response.sendRedirect(request.getContextPath()+"/admin_lend_list.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //查询个人借还日志
    public void personLog(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        ReaderInfo readerInfo = (ReaderInfo) session.getAttribute("readerInfo");
        Integer reader_id = readerInfo.getReader_id();
        //根据读者id查询个人日志
        List<LendList> list = userService.findLog(reader_id);
        try {
            //响应reader_lend_list.html
            objectMapper.writeValue(response.getOutputStream(), list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导出借还日志到excel
    public void downLoad(HttpServletRequest req, HttpServletResponse resp)
    {
        HSSFWorkbook wb = null; //建立新HSSFWorkbook对象
        try {
            wb = new HSSFWorkbook();
            //给excel加密
            Biff8EncryptionKey.setCurrentUserPassword("123456");
            wb.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "user");
            HSSFSheet sheet = wb.createSheet("new sheet"); //建立新的sheet对象
//在sheet里创建一行，参数为行号（第一行，此处可想象成数组）
            HSSFRow row = sheet.createRow((short)0);
//在row里建立新cell（单元格），参数为列号（第一列）

            //第一行设置列名
            row.createCell((short)0).setCellValue("流水号"); //设置cell浮点类型的值
            row.createCell((short)1).setCellValue("book_id"); //设置cell字符类型的值
            row.createCell((short)2).setCellValue("reader_id"); //设置cell布尔类型的值
            row.createCell((short)3).setCellValue("借书日期");
            row.createCell((short)4).setCellValue("归还日期");
       /* HSSFCellStyle cellStyle = wb.createCellStyle(); //建立新的cell样式
        cellStyle.setDataFormat(HSSFDataFormat. getBuiltinFormat("m/d/yy h:mm"));
        HSSFCell csCell =row.createCell((short)5);*/
            //查询数据库来构造excel
            List<LendList> list=userService.downLoad();

            HSSFRow rows=null;
            for (int i = 1; i <list.size()+1 ; i++) {
                rows= sheet.createRow((short)i);

                rows.createCell((short)0).setCellValue(list.get(i-1).getSernum());
                rows.createCell((short)1).setCellValue(list.get(i-1).getBook_id());
                rows.createCell((short)2).setCellValue(list.get(i-1).getReader_id());

                if(list.get(i-1).getLend_date()==null)
                {
                    rows.createCell((short)3).setCellValue("null");
                }else{
                    rows.createCell((short)3).setCellValue(dateToString(list.get(i-1).getLend_date()));
                }
                if(list.get(i-1).getBack_date()==null)
                {
                    rows.createCell((short)4).setCellValue("null");
                }
                else
                    rows.createCell((short)4).setCellValue(dateToString(list.get(i-1).getBack_date()));


            }
            resultInfo.setFlag(true);
            writeValue(resp,resultInfo);
        } catch (Exception e) {
            resultInfo.setFlag(false);
            writeValue(resp,resultInfo);
        }

        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream("lend_log.xls");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            wb.write(fileOut);
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//日期格式转换
    public static String dateToString(Date date) {
        SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd:hh-MM-ss");//日期格式
        String tiem = sformat.format(date);

        return tiem;
    }

    //添加用户
    public void addReader(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ReaderInfo readerInfo = new ReaderInfo();
        //前段String转Date
        DateConverter converter = new DateConverter(null);
        converter.setPattern("yy-MM-dd");
        ConvertUtils.register(converter, Date.class);

        //
        String id = req.getParameter("reader_id");
        Integer userNum = selectUserByOne.selectByOne(id);
        if (userNum == 1) {
            objectMapper.writeValue(resp.getOutputStream(), null);
            return;
        }

        Map<String, String[]> parameterMap = req.getParameterMap();
        try {
            BeanUtils.populate(readerInfo, parameterMap);
            addReaderService.addOneReader(readerInfo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        objectMapper.writeValue(resp.getOutputStream(), id);

    }

    //查询用户信息
    public void selectReader(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ReaderInfo readerInfo = null;

        readerInfo = (ReaderInfo) req.getSession().getAttribute("readerInfo");

        System.out.println(readerInfo);

        String reader_id = req.getParameter("reader_id");

        if (reader_id == null || "".equals(reader_id)) {
                writeValue(resp,readerInfo);
                return;
        } else {
            Integer reader_id_Integer = Integer.parseInt(reader_id);
            readerInfo = selectUserByOne.selectReader(reader_id_Integer);

            if (readerInfo == null) {
                //resultInfo.setFlag(false);
                objectMapper.writeValue(resp.getOutputStream(), false);
                return;
            } else {
                objectMapper.writeValue(resp.getOutputStream(), readerInfo);
            }

        }
    }

    //读者信息修改
    public void readerUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //前段String转Date
        DateConverter converter = new DateConverter(null);
        converter.setPattern("yy-MM-dd");
        ConvertUtils.register(converter, Date.class);
        //ConvertUtils.register(new DateLocaleConverter(), Date.class);

        ReaderInfo readerInfo = new ReaderInfo();
        Map<String, String[]> parameterMap = req.getParameterMap();

        try {
            BeanUtils.populate(readerInfo, parameterMap);

            //Integer reader_id = readerInfo.getReader_id();
            userService.updateReader(readerInfo);

            req.getSession().setAttribute("readerInfo",readerInfo);
            writeValue(resp, readerInfo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    //获取用户name
    public void getReader(HttpServletRequest request, HttpServletResponse response) {
        ReaderInfo readerInfo = (ReaderInfo) request.getSession().getAttribute("readerInfo");
//        System.out.println(reader_id);
        PageInformation information = new PageInformation();
        information.setObj(readerInfo);
        writeValue(response,information);
    }
    //    修改密码
    public void modifyPass(HttpServletRequest request, HttpServletResponse response){
        Integer id = Integer.parseInt(request.getParameter("id"));
        String oldPass = request.getParameter("oldPass");
        String newPass = request.getParameter("newPass");
        ReaderCard readerCard = selectUserByOne.selectReaderCard(id,oldPass);
//        AdminService adminService = new AdminServiceImpl();
//        Admin admin = adminService.selectAdmin(id,oldPass);
//        System.out.println(admin);
        PageInformation information = new PageInformation();
        if(readerCard == null){
            information.setCode(0);
            information.setMessage("密码错误");
            writeValue(response,information);
            return;
        }
        if (selectUserByOne.updateReaderCard(id,newPass) < 1){
            information.setCode(0);
            information.setMessage("修改失败");
            writeValue(response,information);
            return;
        }
        information.setCode(1);
        information.setMessage("修改成功");
        writeValue(response,information);
        writeValue(response, information);
//        reader_id
    }

    //清除用户id
    public void quitReader(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("readerInfo");
        PageInformation information = new PageInformation();
        writeValue(response, information);
    }

    //查询所有用户
    public void allReaderMsg(HttpServletRequest request, HttpServletResponse response) {

        List<ReaderInfo> list = userService.selectAllReader();

        try {
            objectMapper.writeValue(response.getOutputStream(), list);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public void adminSelectReader(HttpServletRequest request, HttpServletResponse response) {

        String reader_id = request.getParameter("readerId");

        //System.out.println(reader_id);
        Integer reader_id_integer = Integer.parseInt(reader_id);

        ReaderInfo readerInfo = selectUserByOne.selectReader(reader_id_integer);

        if (readerInfo == null) {
            resultInfo.setFlag(false);
            writeValue(response, resultInfo);
            return;
        }

        try {
            objectMapper.writeValue(response.getOutputStream(), readerInfo);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //管理员修改用户信息
    public void adminUpdateReader(HttpServletRequest request, HttpServletResponse response) {
        //前端String转Date

        DateConverter converter = new DateConverter(null);
        converter.setPattern("yy-MM-dd");
        ConvertUtils.register(converter, Date.class);

        ReaderInfo readerInfo = new ReaderInfo();
        Map<String, String[]> parameterMap = request.getParameterMap();

        try {
            BeanUtils.populate(readerInfo, parameterMap);

            userService.updateReader(readerInfo);
            writeValue(response, true);
            //userService.updateReader(readerInfo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    //删除用户 author:jm
    public void del_reader(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String readerId = request.getParameter("readerId");

        userService.deleteReader(readerId);

        response.sendRedirect(request.getContextPath() + "/admin_readers.html");

        //writeValue(response,true);

    }
    //将excel文件导入mysql
    static HSSFRow row;
    public void  upLoad(HttpServletRequest request, HttpServletResponse response) throws IOException {

        FileInputStream fis = null;
        try {
            JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
            fis = new FileInputStream(new File("lend_log.xls"));
            HSSFWorkbook workbook = new HSSFWorkbook(fis);
            HSSFSheet spreadsheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = spreadsheet.iterator();
            for (int i = 1; i < spreadsheet.getLastRowNum()+1; i++) {
                double serNum = spreadsheet.getRow(i).getCell(0).getNumericCellValue();
                double book_id = spreadsheet.getRow(i).getCell(1).getNumericCellValue();
                double reader_id = spreadsheet.getRow(i).getCell(2).getNumericCellValue();
                String lend_date = spreadsheet.getRow(i).getCell(3).getStringCellValue();
                String back_date = spreadsheet.getRow(i).getCell(4).getStringCellValue();
                if ("null".equals(back_date)){
                    String sql = "insert into lend_list values(?,?,?,?,null)";
                    template.update(sql,serNum,book_id,reader_id,lend_date);
                }else {
                    String sql = "insert into lend_list values(?,?,?,?,?)";
                    template.update(sql,serNum,book_id,reader_id,lend_date,back_date);
                }
            }
            resultInfo.setFlag(true);
            writeValue(response,resultInfo);
        } catch (Exception e) {
            resultInfo.setFlag(false);
            writeValue(response,resultInfo);
        }


        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void writeValue(HttpServletResponse response, Object values) {
//    响应页面
        try {
            objectMapper.writeValue(response.getOutputStream(), values);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
